import { Request } from '../../models/request.model';
import { StorageService } from '../../services/storage.service';
import { formatDate, truncateString } from '../../utils/utils';

/**
 * 历史记录和保存请求管理类
 */
export class HistoryManager {
    // 保存和历史
    private savedRequestsList: HTMLDivElement;
    private historyRequestsList: HTMLDivElement;
    
    // 回调函数
    private onRequestSelect: (request: Request) => void;

    /**
     * 构造函数
     * @param onRequestSelect 选择请求的回调函数
     */
    constructor(onRequestSelect: (request: Request) => void) {
        this.onRequestSelect = onRequestSelect;

        // 获取DOM元素
        this.savedRequestsList = document.getElementById('saved-requests-list') as HTMLDivElement;
        this.historyRequestsList = document.getElementById('history-requests-list') as HTMLDivElement;
        
        // 初始化
        this.loadData();
    }
    
    /**
     * 加载数据
     */
    private async loadData(): Promise<void> {
        await this.loadSavedRequests();
        await this.loadHistoryRequests();
    }

    /**
     * 重新加载数据
     */
    public async reload(): Promise<void> {
        await this.loadData();
    }

    /**
     * 加载保存的请求
     */
    private async loadSavedRequests(): Promise<void> {
        try {
            const savedRequests = await StorageService.getSavedRequests();

            // 清空列表
            this.savedRequestsList.innerHTML = '';

            if (savedRequests.length === 0) {
                // 显示空状态
                const emptyState = document.createElement('div');
                emptyState.className = 'empty-state';
                emptyState.textContent = '没有保存的请求';
                this.savedRequestsList.appendChild(emptyState);
                return;
            }

            // 添加保存的请求
            savedRequests.forEach(request => {
                const requestElement = this.createRequestElement(request, 'saved');
                this.savedRequestsList.appendChild(requestElement);
            });
        } catch (error) {
            console.error('Error loading saved requests:', error);
        }
    }

    /**
     * 加载历史请求
     */
    private async loadHistoryRequests(): Promise<void> {
        try {
            const history = await StorageService.getHistory();

            // 清空列表
            this.historyRequestsList.innerHTML = '';

            if (history.length === 0) {
                // 显示空状态
                const emptyState = document.createElement('div');
                emptyState.className = 'empty-state';
                emptyState.textContent = '没有历史记录';
                this.historyRequestsList.appendChild(emptyState);
                return;
            }

            // 添加历史请求
            history.forEach(request => {
                const requestElement = this.createRequestElement(request, 'history');
                this.historyRequestsList.appendChild(requestElement);
            });
        } catch (error) {
            console.error('Error loading history requests:', error);
        }
    }

    /**
     * 创建请求元素
     * @param request 请求对象
     * @param type 类型（saved或history）
     * @returns 请求元素
     */
    private createRequestElement(request: Request, type: 'saved' | 'history'): HTMLDivElement {
        const element = document.createElement('div');
        element.className = `${type}-item`;

        // 添加请求方法
        const methodSpan = document.createElement('span');
        methodSpan.className = 'item-method';
        methodSpan.textContent = request.method;
        element.appendChild(methodSpan);

        // 添加URL
        const urlSpan = document.createElement('span');
        urlSpan.className = 'item-url';
        urlSpan.textContent = truncateString(request.url, 50);
        urlSpan.title = request.url;
        element.appendChild(urlSpan);

        // 添加日期
        if (request.createdAt) {
            const dateSpan = document.createElement('div');
            dateSpan.className = 'item-date';
            dateSpan.textContent = formatDate(request.createdAt);
            element.appendChild(dateSpan);
        }

        // 添加点击事件
        element.addEventListener('click', () => {
            this.onRequestSelect(request);
        });

        return element;
    }
} 